<template>
    <el-container style="flex-direction: column; height: 100vh;">
        <!-- 顶部栏 -->
        <HeaderComponent :userInfo="this.userInfo" />

        <!-- 主内容区 -->
        <el-container style="flex-direction: row; height: 100vh;">
            <!-- 侧边栏 -->
            <SidebarComponent />

            <!-- 公告列表 -->
            <el-main>
                <div class="forum-admin-container">
                    <!-- 搜索栏 -->
                    <div class="search-bar">
                        <el-input v-model="searchKey" placeholder="作者" clearable
                            style="width: 200px; margin-right: 50px"></el-input>

                        <el-date-picker v-model="selectedDate" type="daterange" range-separator="至"
                            start-placeholder="开始日期" end-placeholder="结束日期" value-format="timestamp"
                            clearable></el-date-picker>
                    </div>

                    <!-- 帖子列表 -->
                    <el-table :data="filteredPosts" :key="filteredPosts.length" style="width: 100%" v-loading="loading" @sort-change="handleSortChange">
                        <el-table-column prop="content" label="内容">
                            <template slot-scope="{ row }">
                                <div class="clickable-content" @click.stop="showPostDetail(row)">
                                    {{ row.content }}
                                </div>
                            </template>
                        </el-table-column>

                        <el-table-column prop="username" label="作者" width="120"></el-table-column>

                        <el-table-column prop="likes" label="点赞" width="100" sortable="custom"></el-table-column>

                        <el-table-column prop="comments.length" label="评论" width="100"
                            sortable="custom"></el-table-column>

                        <el-table-column prop="releaseTime" label="发布时间" width="180"></el-table-column>

                        <!-- <el-table-column label="权重" width="200">
                            <template slot-scope="{row}">
                                <el-input-number v-model="row.weight" :min="0" :max="10" size="mini"
                                    @change="updatePostWeight(row)"></el-input-number>
                            </template>
</el-table-column> -->

                        <el-table-column label="操作" width="120">
                            <template slot-scope="{row}">
                                <el-button type="danger" icon="el-icon-delete" circle
                                    @click="handleDeletePost(row)"></el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <!-- 帖子详情弹窗 -->
                    <el-dialog title="帖子详情" :visible.sync="postDialogVisible" width="70%">
                        <div class="post-content">
                            <div class="comment-header">
                                <el-avatar :size="64" :src="currentPost.image"></el-avatar>
                                <div style="text-align: left; margin-left: 20px;">

                                    <span class="author">{{ currentPost.username }}</span>
                                    <span class="time">{{ formatTime(currentPost.releaseTime) }}</span>
                                </div>
                            </div>
                            <div class="comment-content" style="text-align: left;">{{ currentPost.content }}</div>
                        </div>

                        <!-- 评论列表 -->
                        <div class="comment-list">
                            <div v-for="comment in currentPost.comments" :key="comment.id" class="comment-item">
                                <div class="comment-header">
                                    <el-avatar :size="32" :src="comment.image"></el-avatar>
                                    <div class="comment-info" style="text-align: left;">
                                        <span class="author">{{ comment.username }}</span>
                                        <span class="time">{{ formatTime(comment.releaseTime) }}</span>
                                    </div>
                                    <el-button type="danger" icon="el-icon-delete" size="mini" class="delete-btn"
                                        @click="handleDeleteComment(comment)"></el-button>
                                </div>
                                <div class="comment-content" style="text-align: left;">{{ comment.content }}</div>
                            </div>
                        </div>
                    </el-dialog>
                </div>
            </el-main>
        </el-container>
    </el-container>
</template>

<script>
import HeaderComponent from '@/components/property_components/PropertyHeader.vue';
import SidebarComponent from '@/components/property_components/PropertySidebar.vue';
import { parseJwt } from '@/utils/parseJWT';
import service from '@/utils/request';

export default {
    components: {
        HeaderComponent,
        SidebarComponent
    },
    data() {
        return {
            userInfo: {},
            loading: false,
            posts: [],
            currentPost: {},
            postDialogVisible: false,
            searchKey: '',
            selectedDate: [],
            sortParams: {
                prop: null,
                order: null
            },
            filteredPosts: []
        }
    },
    watch: {
        searchKey() {
            this.applyFilters();
        },
        selectedDate() {
            this.applyFilters();
        }
    },
    mounted() {
        this.userInfo = parseJwt(localStorage.getItem('token')).payload || {};
        this.getPosts();
    },
    methods: {
        getPosts() {
            this.loading = true;
            service.get('/api/user/forum/getPosts')
               .then(response => {
                    const result = response.data;
                    if (result.code !== 1) {
                        this.$message.error(result.msg);
                        console.error('获取帖子数据失败:', result.msg);
                        return;
                    }

                    // 初始化帖子数据，添加响应式属性
                    this.posts = result.data.map(post => ({
                        ...post,
                        showComments: false,
                        comments: post.comments || [] // 初始评论数据
                    }));

                    // 并行获取所有帖子的评论
                    const commentPromises = this.posts.map(post =>
                        service.get(`/api/user/forum/getComments/${post.id}`)
                           .then(commentResponse => {
                                const commentResult = commentResponse.data;
                                if (commentResult.code === 1) {
                                    // 更新评论数据，Vue会自动检测数组变更
                                    post.comments = commentResult.data;
                                } else {
                                    this.$message.error(commentResult.msg);
                                    console.error('获取评论数据失败:', commentResult.msg);
                                }
                            })
                           .catch(error => {
                                this.$message.error('获取评论失败');
                                console.error('获取评论数据失败:', error);
                            })
                    );

                    return Promise.all(commentPromises);
                })
               .then(() => {
                    // 所有数据加载完成，可执行后续操作
                    console.log('所有帖子及评论已加载:', this.posts);
                    this.applyFilters();
                    this.loading = false;
                })
               .catch(error => {
                    if (!error.response) { // 避免重复显示错误信息
                        this.$message.error('获取帖子失败');
                    }
                    console.error('获取帖子数据失败:', error);
                    this.loading = false;
                });
        },
        handleSortChange({ prop, order }) {
            this.sortParams = { prop, order };
            this.applyFilters();
        },
        showPostDetail(post) {
            this.currentPost = post;
            this.postDialogVisible = true;
        },
        async handleDeletePost(post) {
            service.get(`/api/admin/forum/deletePost/${post.id}`).then(result => {
                result = result.data;
                if (result.code == 1) {
                    this.$message.success('删除成功');
                    this.getPosts();
                } else {
                    this.$message.error(result.msg);
                }
            }).catch(error => {
                this.$message.error('删除失败');
                console.error(error);
            });
        },
        async handleDeleteComment(comment) {
            service.get(`/api/admin/forum/deleteComment/${comment.id}`).then(result => {
                result = result.data;
                if (result.code == 1) {
                    this.$message.success('删除成功');
                    this.getPosts();
                    this.postDialogVisible = false;
                } else {
                    this.$message.error(result.msg);
                }
            }).catch(error => {
                this.$message.error('删除失败');
                console.error(error);
            });
        },
        formatTime(timestamp) {
            return new Date(timestamp).toLocaleString();
        },
        applyFilters() {
            let filtered = this.posts;

            // 搜索过滤
            if (this.searchKey) {
                filtered = filtered.filter(post => post.username.includes(this.searchKey));
            }

            // 日期过滤
            if (this.selectedDate && this.selectedDate.length === 2) {
                const [startDate, endDate] = this.selectedDate;
                filtered = filtered.filter(post => post.releaseTime >= startDate && post.releaseTime <= endDate);
            }

            // 排序
            if (this.sortParams.prop && this.sortParams.order) {
                const { prop, order } = this.sortParams;
                const multiplier = order === 'ascending' ? 1 : -1;
                filtered.sort((a, b) => {
                    if (prop === 'comments.length') {
                        return multiplier * (a.comments.length - b.comments.length);
                    }
                    // 移除日期排序逻辑
                    return multiplier * (a[prop] - b[prop]);
                });
            }

            this.filteredPosts = filtered;
        }
    }
};
</script>

<style>
/* 新增表格居中样式 */
.forum-admin-container .el-table th>.cell {
    text-align: center !important;
}

.forum-admin-container .el-table td>.cell {
    text-align: center !important;
}

/* 调整操作按钮居中 */
.forum-admin-container .el-table-column--operation .cell {
    display: flex;
    justify-content: center;
}

/* 调整评论删除按钮位置 */
.delete-btn {
    margin-left: auto;
}

.forum-admin-container {
    padding: 20px;
    width: 100%;
    margin: 0 auto;
}

.search-bar {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
}

.post-title {
    cursor: pointer;
    color: #409EFF;
}

.post-title:hover {
    text-decoration: underline;
}

.post-content {
    padding: 15px;
    margin-bottom: 20px;
    background: #f8f9fa;
    border-radius: 4px;
}

.comment-list {
    max-height: 60vh;
    overflow-y: auto;
}

.comment-item {
    padding: 12px;
    margin-bottom: 15px;
    border-bottom: 1px solid #eee;
}

.comment-item:last-child {
    border-bottom: none;
}

.comment-header {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
}

.comment-info {
    flex: 1;
    margin-left: 12px;
}

.comment-info .author {
    font-weight: 500;
    margin-right: 10px;
}

.comment-info .time {
    color: #909399;
    font-size: 0.9em;
}

.delete-btn {
    opacity: 0.7;
}

.delete-btn:hover {
    opacity: 1;
}

.comment-content {
    color: #606266;
    line-height: 1.6;
    margin-left: 44px;
}

.el-table .cell {
    white-space: nowrap;
}
</style>    